<template>
  <div class="table-module">
    <!-- 查询 -->
    <div class="query" ref="queryRef">
      <div class="query-content">
        <el-form :model="props.tableModule!.queryForm" style="display: flex;" label-position="left" class="query-form">
          <el-form-item :label="item.label" style="margin-right: 20px; margin-bottom: 0;" v-for="item in props.tableModule!.query" :key="item.prop">
            <el-input v-model="props.tableModule!.queryForm[item.prop]" :placeholder="'输入' + item.label + '关键字'" clearable v-if="item.type == 'text'" />
            <el-select v-model="props.tableModule!.queryForm[item.prop]" clearable style="width: 200px;" :placeholder="'选择' + item.label" v-else-if="item.type == 'select'">
              <el-option v-for="cItem in item.options" :label="cItem.label" :value="cItem.value" />
            </el-select>
            <el-date-picker v-model="props.tableModule!.queryForm[item.prop]" clearable type="datetimerange"
                            format="YYYY/MM/DD hh:mm:ss" value-format="YYYY/MM/DD HH:mm:ss" range-separator="至" start-placeholder="开始时间"
                            end-placeholder="结束时间" v-else-if="item.type == 'date'" />
          </el-form-item>
        </el-form>
      </div>
      <div class="slot">
        <el-button @click="Search" type="primary" plain>查询</el-button>
        <el-button @click="Recover">重置</el-button>
        <!-- slot插槽，供使用页添加表格其他操作）-->
        <slot name="event"></slot>
        <!-- 动态表头显示 -->
        <el-popover placement="bottom" title="表格配置" :width="200" trigger="click">
          <div v-for="(item, index) in props.tableModule?.columns" :key="index">
            <el-checkbox v-model="item.show" :label="item.label" :true-label="1" :false-label="0" />
          </div>
          <template #reference>
<!--            <el-button :icon="Operation"></el-button>-->
          </template>
        </el-popover>
      </div>
    </div>
    <!-- 表格 -->
    <el-table :data="props.tableModule!.dataList" border
              :style="{ 'height': `calc(100vh - ${queryHeight + 156}px)` }" v-loading="props.tableModule!.loading"
              :row-class-name="tableRowClassName" :cell-class-name="tableCellClassName" @cell-dblclick="cellDblClick"
              id="el-table" ref="tableRef">
      <el-table-column type="selection" width="50" align="center" />
      <!-- columns表格配置数据 -->
      <template v-for="(item) in props.tableModule!.columns">
        <!-- 循环 columns 紧接着判断每个字段的类型 -->
        <el-table-column :prop="item.prop" :label="item.label" :align="item.align || 'left'" :width="item.width"
                         :min-width="item.min_width" :fixed="item.fixed" v-if="item.show">
          <template #default="scope">
            <!-- switch时使用switch开关组件，并且绑定好我们配置的属性 -->
            <div v-if="item.type == 'status'">
              <el-tag :type="fieldChange(scope.row[item.prop])">{{ item.option[scope.row[item.prop]] }}</el-tag>
            </div>
            <div v-else-if="item.type == 'feedback'">
              <el-tag :type="fieldShow(scope.row[item.prop])">{{ item.option[scope.row[item.prop]] }}</el-tag>
            </div>
            <div v-else-if="item.type == 'image'">
              <el-image style="width: 60px; height: 60px" :src="getImgUrl(scope.row[item.prop])"
                        :preview-src-list="[getImgUrl(scope.row[item.prop])]" :preview-teleported="true">
              </el-image>
            </div>
            <div v-else-if="item.type == 'textarea'">
              <el-input
                  v-model="item.value"
                  style="width: 240px"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入内容"
              />
            </div>
            <div v-else-if="item.type == 'time'">{{ scope.row[item.prop] }}</div>
            <!-- 类型都不匹配时直接展示 -->
            <div v-else>{{ scope.row[item.prop] }}</div>
          </template>
        </el-table-column>
      </template>
      <!-- 这里的插槽用于列表的操作列 -->
      <slot name="tableColumn"></slot>
    </el-table>
    <!-- 分页 -->
    <div class="page">
      <el-pagination :current-page="props.tableModule?.pages.page" :page-size.sync="props.tableModule?.pages.limit"
                     :page-sizes="pageSizes" :layout="layout" :total="props.tableModule?.pages.total" @size-change="sizeChange"
                     @current-change="currentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, toRefs } from 'vue'
import { ElTable } from 'element-plus';
// import { Operation } from '@element-plus/icons-vue'

const props = defineProps({
  tableModule: Object, // 由父组件传递而来
  layout: { // 分页功能配置
    type: String,
    default: "total, sizes, prev, pager, next, jumper",
  },
  pageSizes: { // 分页：每页条数配置
    type: Array,
    default() {
      return [10, 20, 30, 50];
    },
  },
})

const state = reactive({
  rowIndex: 0, // 行索引 用于可编辑单元格
  columnIndex: 0, // 列索引 用于可编辑单元格
  queryHeight: 0,
})

const {
  // rowIndex,
  // columnIndex,
  queryHeight,
} = toRefs(state)

const queryRef = ref<HTMLElement | null>(null);

onMounted(() => {
  // 这里拿到query模块的高度，适配页面高度的
  // setTimeout(() => {
  //   state.queryHeight = queryRef.value!.clientHeight
  // }, 100);

  // 为每个表格配置项添加show属性，默认1为显示状态
  props.tableModule!.columns.forEach((item: any) => {
    item.show = 1
  })
})

function fieldChange(row: any) {
  switch (row) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'primary'
  }
}

function fieldShow(row: any) {
  switch (row) {
    case 1:
      return 'danger'
    case 2:
      return 'warning'
    case 3:
      return 'success'
    case 4:
      return 'info'
    case 5:
      return 'primary'
  }
}

// 编辑单元格 ----------
// 为每一行返回固定的className
function tableRowClassName({ row, rowIndex }: { row: any; rowIndex: number }) {
  row.Indexs = rowIndex;
}

// 为所有单元格设置一个固定的 className
function tableCellClassName({ column, columnIndex }: { column: any; columnIndex: number }) {
  column.Indexs = columnIndex;
}

// el-table单元格双击事件
function cellDblClick(row: any, column: any, cell: HTMLElement, event: MouseEvent) {
  state.rowIndex = row.Indexs
  state.columnIndex = column.Indexs
}

// 每页条数切换时触发
function sizeChange(item: number) {
  props.tableModule!.pages.limit = item
  props.tableModule?.callback() // 父组件绑定的回调
}

// 页数切换时触发
function currentChange(item: number) {
  props.tableModule!.pages.page = item
  props.tableModule?.callback()
}

const tableRef = ref(null)

defineExpose({
  tableRef
});

// 声明自定义事件
const emit = defineEmits(['search', 'recover'])

// 点击查询按钮时触发
function Search() {
  props.tableModule?.callback()
  emit('search');
}

// 点击重置触发
function Recover() {
  props.tableModule?.callback()
  props.tableModule!.queryForm = {}
  emit('recover')
}

const getImgUrl = (filename: string) => {
  try {
    const match: RegExpMatchArray | null = filename.match(/^([^,]+)/);
    if (match && match[1] && match[1].trim() !== '') {
      return `http://localhost:8018/file/image?imageName=${encodeURIComponent(match[1])}`;
    }
  }catch (error) {
    return filename;
  }
}
</script>

<style scoped lang="scss">
.table-module {
  .query {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 10px;

    .query-content {
      display: flex;
      align-items: flex-start;

      .query-form {
        .el-form-item {
          margin-right: 20px;
        }

        .el-input {
          width: 200px;
        }

        ::v-deep(.el-select) {
          .el-input {
            width: 200px;
          }
        }
      }
    }

    .slot {
      display: flex;
      justify-content: flex-end;
      padding-right: 48px;
    }
  }

  .page {
    margin-top: 10px;
  }
}

</style>
